package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.glory.cqaospda.R
import com.glory.cqaospda.adapter.FixtureBindAdapter
import com.glory.cqaospda.adapter.LotMateriaAdapter
import com.glory.cqaospda.adapter.MateriaAdapter
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.*
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.StartjobModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText
import kotlinx.android.synthetic.main.activity_startjob.*
import kotlinx.android.synthetic.main.activity_title.*
import kotlinx.android.synthetic.main.carrier_layout.*
import kotlinx.android.synthetic.main.carriertape_layout.*
import kotlinx.android.synthetic.main.cover_layout.*
import kotlinx.android.synthetic.main.lotcarriertape_layout.*
import kotlinx.android.synthetic.main.lotcover_layout.*
import kotlinx.android.synthetic.main.lotplug_layout.*
import kotlinx.android.synthetic.main.lotreel_layout.*
import kotlinx.android.synthetic.main.matrrial_lot.*
import kotlinx.android.synthetic.main.plug_layout.*
import kotlinx.android.synthetic.main.reel_layout.*
import java.lang.Exception


class StartjobActivity : BaseActivity<StartjobModel>() {

    var mFixtureBindAdapter: FixtureBindAdapter? = null
    var eqpInfoBean: EqpInfoBean? = null
    var lotList = ArrayList<LotInfoBean>()
    var lotLists = ArrayList<LotInfoBean>()
    var lotidList = ArrayList<String>()
    var CustomerName: String = ""
    var FactoryPackage: String = ""
    var CustomerDevice: String = ""
    var EquipmentName: String = ""
    var isLot = ""
    var stepName = ""
    var lotid = ""
    var mainLot = true
    var lotMateriaAdapter: LotMateriaAdapter? = null
    var type = ""
    var mBatchTrackIn = ""
    var MaterialInfoList = ArrayList<BatchLotBean.Material>()
    var BatchLotList = ArrayList<BatchLotBean>()
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@StartjobActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }
    override fun initData() {

        queryEqpData(etEqpId)
        queryLotData(etLotId, "etLotId")
        queryLotData(etLotsId, "etLotsId")
        tvSetTrackOutNum.setOnClickListener {
            if (Constant.isFastClick()) {
                intent.putExtra("eqpID", etEqpId.text.toString())
                intent.putExtra("TypeActivity","Startjob2")
                intent.setClass(this, MaterialReplaceActivity::class.java)
                startActivity(intent)
            }
        }

        tvBaseSubmit.setOnClickListener {
            if (Constant.isFastClick()) {
//                if (tvTrackIn.isEnabled) {
//                    viewModel.defUI.toastEvent.value = ToastMessageBean("未进行准备进站操作", true)
//                    return@setOnClickListener
//                }

                mBatchTrackIn = "EMS_BatchTrackIn"
                BatchLotList.clear()
                if (eqpInfoBean == null) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前设备数据为空", true)
                    return@setOnClickListener
                }
                if (mFixtureBindAdapter!!.data.size == 0) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前批次信息为空", true)
                    return@setOnClickListener
                }
                if (Constant.eqpMaterialsBean!!.mMaterialslist!! == null) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前物料为空", true)
                    return@setOnClickListener
                }

                MaterialInfoList.clear()
                val data = mFixtureBindAdapter!!.data
                for (s in data) {
                    val batchLotBean = BatchLotBean()
                    batchLotBean.lotNo = s.mLotId
                    batchLotBean.carryList = ""
                    batchLotBean.batchLotType = s.batchLotType
                    BatchLotList.add(batchLotBean)
                }
                if (Constant.eqpMaterialsBean != null) {
                    for (materialslist in Constant.eqpMaterialsBean!!.mMaterialslist!!) {
                        val material = BatchLotBean().Material()
                        material.materialCode =
                            if (materialslist!!.mMaterialCode == null) "" else materialslist!!.mMaterialCode
                        material.materialId =
                            if (materialslist!!.mMaterialId == null) "" else materialslist!!.mMaterialId
                        material.vonderCode =
                            if (materialslist!!.mVendorCode == null) "" else materialslist!!.mVendorCode
                        MaterialInfoList.add(material)
                    }
                }

                val map = JsonObject()
                map.addProperty("StepName", stepName)
                map.addProperty("EquipmentName", etEqpId.text.toString())
                map.addProperty("BatchLotCount", data.size)
                map.addProperty("MainLotNo", lotid)
                map.add("BatchLotList", JsonParser().parse(Gson().toJson(BatchLotList)).asJsonArray)
                map.add(
                    "MaterialInfo",
                    JsonParser().parse(Gson().toJson(MaterialInfoList)).asJsonArray
                )

                viewModel.defaultBatchTrackIn(map, "EMS_BatchTrackIn")
            }
        }

        tvTrackIn.setOnClickListener {
            if (Constant.isFastClick()) {
                mBatchTrackIn = "EMS_BatchTrackInPre"
                BatchLotList.clear()
                if (eqpInfoBean == null) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前设备数据为空", true)
                    return@setOnClickListener
                }
                if (mFixtureBindAdapter!!.data.size == 0) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前批次信息为空", true)
                    return@setOnClickListener
                }
                if (Constant.eqpMaterialsBean!!.mMaterialslist!! == null) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前物料为空", true)
                    return@setOnClickListener
                }

                MaterialInfoList.clear()
                val data = mFixtureBindAdapter!!.data
                for (s in data) {
                    val batchLotBean = BatchLotBean()
                    batchLotBean.lotNo = s.mLotId
                    batchLotBean.carryList = ""
                    batchLotBean.batchLotType = s.batchLotType
                    BatchLotList.add(batchLotBean)
                }
                if (Constant.eqpMaterialsBean != null) {
                    for (materialslist in Constant.eqpMaterialsBean!!.mMaterialslist!!) {
                        val material = BatchLotBean().Material()
                        material.materialCode =
                            if (materialslist!!.mMaterialCode == null) "" else materialslist!!.mMaterialCode
                        material.materialId =
                            if (materialslist!!.mMaterialId == null) "" else materialslist!!.mMaterialId
                        material.vonderCode =
                            if (materialslist!!.mVendorCode == null) "" else materialslist!!.mVendorCode
                        MaterialInfoList.add(material)
                    }
                }

                val map = JsonObject()
                map.addProperty("StepName", stepName)
                map.addProperty("EquipmentName", etEqpId.text.toString())
                map.addProperty("BatchLotCount", data.size)
                map.addProperty("MainLotNo", lotid)
                map.add("BatchLotList", JsonParser().parse(Gson().toJson(BatchLotList)).asJsonArray)
                map.add(
                    "MaterialInfo",
                    JsonParser().parse(Gson().toJson(MaterialInfoList)).asJsonArray
                )

                viewModel.defaultBatchTrackIn(map, "EMS_BatchTrackInPre")
            }
        }

        ivTypeArrow.setOnClickListener {
            if (lineMaterial.visibility == View.GONE) {
                ivTypeArrow.setImageResource(R.drawable.down)
                lineMaterial.visibility = View.VISIBLE
            } else {
                ivTypeArrow.setImageResource(R.drawable.left)
                lineMaterial.visibility = View.GONE
            }
        }

        ivLotTypeArrow.setOnClickListener {
            if (lineLotMaterial.visibility == View.GONE) {
                ivLotTypeArrow.setImageResource(R.drawable.down)
                lineLotMaterial.visibility = View.VISIBLE
            } else {
                ivLotTypeArrow.setImageResource(R.drawable.left)
                lineLotMaterial.visibility = View.GONE
            }
        }

        viewModel.defUI.callObserve.observe(this) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        val lotsBean = it.item as LotInfoBean

                        when (type) {
                            "engineer" -> {
                                if (lotsBean.mLotClass != "Engineer") {
                                    viewModel.defUI.toastEvent.value =
                                        ToastMessageBean("当前页面为工程批页面，批次不属于工程批批次", false)
                                    return@observe
                                }
                            }
                            "header" -> {
                                if (lotsBean.mLotClass == "Engineer") {
                                    viewModel.defUI.toastEvent.value =
                                        ToastMessageBean("当前批次为工程批批次", false)
                                    return@observe
                                }
                            }
                        }

                        stepName = lotsBean.mStepName
                        lotidList.clear()
                        for (adapterData in mFixtureBindAdapter!!.data) {
                            lotidList.add(adapterData.mLotId)
                        }

                        if (lotidList.contains(lotsBean.mLotId)) {
                            viewModel.defUI.toastEvent.value =
                                ToastMessageBean("当前批次已加载到列表中", false)
                        } else {
                            CustomerName = lotsBean.mCustomerName
                            FactoryPackage = lotsBean.mFactoryPackage
                            CustomerDevice = lotsBean.mCustomerDevice
                            tvCustomerName.text = lotsBean.mCustomerName
                            tvPackage.text = lotsBean.mFactoryPackage
                            tvDevice.text = lotsBean.mCustomerDevice
                            if ("etLotId".equals(isLot)) {
                                lotsBean.isLot = "etLotId"
                                lotsBean.batchLotType = "MainLot"
                                Constant.lotID = lotsBean.mLotId
                                val map = JsonObject()
                                map.addProperty("LotNo", Constant.lotID)
                                map.addProperty("EquipmentName", etEqpId.text.toString())
                                viewModel.defaultBOM(map)
                            } else {
                                lotsBean.isLot = "etLotsId"
                                lotsBean.batchLotType = "ResidueLot"
                            }
                            lotList.add(lotsBean)
                            mFixtureBindAdapter!!.setList(lotList)
                        }
                        if (lotsBean.mState != "Idle" && lotsBean.mState != "TrackOut") {
                            etLotId.setText("")
                            lotid = lotsBean.mLotId
                            lotLists.clear()
                            lotLists.add(lotsBean)
                            CustomerName = lotsBean.mCustomerName
                            FactoryPackage = lotsBean.mFactoryPackage
                            CustomerDevice = lotsBean.mCustomerDevice
                            intent.putExtra("type", "State")
                            intent.putExtra("lotID", lotsBean.mLotId)
                            intent.setClass(this, SkipDialogActivity::class.java)
                            startActivityForResult(intent, 1)
                        }

                    }
                    2 -> {
                        FreeApi_LogUtils.saveErrorMessages(mBatchTrackIn, "mBatchTrackIn")
                        if (mBatchTrackIn == "EMS_BatchTrackInPre") {
                            tvTrackIn.isEnabled = false
                            tvTrackIn.setTextColor(Color.parseColor("#9F9D9D"));
                            viewModel.defUI.toastEvent.value = ToastMessageBean("准备进站成功", true)
                            return@observe
                        }
                        val trackInInfoBean = it.item as TrackInInfoBean

                        viewModel.defUI.toastEvent.value = ToastMessageBean("成功进站", true)

                        intent.putExtra("lotList", lotList)
                        intent.putExtra("tipe", trackInInfoBean.trackininfo)
                        intent.putExtra("CustomerName", CustomerName)
                        intent.putExtra("FactoryPackage", FactoryPackage)
                        intent.putExtra("CustomerDevice", CustomerDevice)
                        intent.putExtra("EquipmentName", tvHandle.text.toString())
                        intent.putExtra("EquipmentStatus", tvMESstate.text.toString())
                        intent.putExtra("LotId", etLotId.text.toString())
                        intent.putExtra("eqpId", etEqpId.text.toString())
                        intent.setClass(this, Startjob2Activity::class.java)
                        startActivity(intent)
                    }
                    3 -> {
                        val eqpBean = it.item as EqpInfoBean
                        eqpInfoBean = eqpBean
                        tvHandle.text =
                            if (eqpBean.EquipmentName == null) "" else eqpBean.EquipmentName
                        tvMESstate.text =
                            if (eqpBean.EquipmentStatus == null) "" else eqpBean.EquipmentStatus
                        tvLocalEquipmentStatus.text =
                            if (eqpBean.EquipmentStatus == null) "" else eqpBean.EquipmentStatus
//                    tvLocalEquipmentStatus.text =
//                        if (eqpBean.LocalEquipmentStatus == null) "" else eqpBean.LocalEquipmentStatus
                        etLotId.requestFocus()
                        viewModel.defaultEqpMaterials(etEqpId.text.toString())
                        if (eqpBean.mLotList != null && eqpBean.mLotList.isNotEmpty()) {
                            lotLists.clear()
                            for (eqpinfo in eqpBean.mLotList) {
                                val lotInfoBean = LotInfoBean(
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    eqpinfo.mLotNo,
                                    "",
                                    arrayListOf(),
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    arrayListOf()
                                )
                                lotLists.add(lotInfoBean)
                            }
                            intent.putExtra("type", "State")
                            intent.putExtra("lotID", "State")
                            intent.setClass(this, SkipDialogActivity::class.java)
                            startActivityForResult(intent, 1)
                        }
                    }
                    4 -> {
                        Constant.eqpMaterialsBean = it.item as EqpMaterialsBean
                        materialsData()
                    }
                    5 -> {
                        val bom = it.item as BomBean

                        val lotMatreialList = ArrayList<BomBean.Materialslist>()
                        if (bom.mBOMList != null && bom.mBOMList!!.size > 0) {
                            for (bomList in bom.mBOMList!!) {
                                if (bomList!!.mStepID == stepName) {
                                    lotMatreialList.add(bomList)
                                }
                            }
                        }
                        lotMaterialsData(lotMatreialList,bom.mLotID!!)
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }

    }

    private fun queryLotData(
        editText: EditText?,
        isLot: String,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            if (editText != etLotId) {
                etLotsId.setText("")
                etLotsId.hint = "请扫描子批次ID"
            }
            if (FixtureBindAdapter.getIsMainLot()){
                viewModel.defUI.toastEvent.value = ToastMessageBean("主批只能添加一次，请删除列表后重新扫描！")
                return@setEditTextListener
            }
            this.isLot = isLot
            if (isLot == "etLotId") {
                etLotsId.requestFocus()
                lotid = s!!
                mainLot = false
            }
            if (eqpInfoBean == null) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请先扫描设备", true)
            } else {
                viewModel.defaultLotInfo(s!!, isLot, eqpInfoBean!!.EquipmentName)
            }

        }

    }

    private fun queryEqpData(
        editText: FreeUI_ClearEditText?,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            viewModel.defaultEqpInfo(s!!)
        }

    }

    private fun queryEqpMaterialsData(
        editText: FreeUI_ClearEditText?,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            viewModel.defaultEqpMaterials(s!!)
        }

    }

    override fun initView(savedInstanceState: Bundle?) {
        tvBaseSubmit.text = "开始作业"
        val title = intent.getStringExtra("title")
        tvTitle.text = title

        val instance = MyApp.instance
        instance!!.handler = handler
        tvUserName.text = Constant.UserName
        tvTrackIn.visibility = View.VISIBLE
        FreeApi_ActivityManager.getActivityManager().addActivity(this)

        initRecyclerView(rvLotList, this)
        mFixtureBindAdapter = FixtureBindAdapter(lotList, false, "", "")
        rvLotList.adapter = mFixtureBindAdapter


    }

    override fun layoutId(): Int {
        return R.layout.activity_startjob
    }

    private fun materialsData() {

        val carriertapeData = filteringData("carriertape")
        initRecyclerView(rvCarrierList, this)
        val carriertapeAdapter = MateriaAdapter(carriertapeData, "carriertapeData")
        rvCarrierList.adapter = carriertapeAdapter
        if (carriertapeData.isEmpty()) {
            reCarriertape.visibility = View.GONE
        } else {
            reCarriertape.visibility = View.VISIBLE
        }
        carriertapeAdapter.setOnItemClickListener {data ->
            intent.putExtra("type", "materiaAdapter")
            intent.putExtra("materiaData", data)
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivity(intent)
        }

        val reelData = filteringData("reel")
        initRecyclerView(rvReelList, this)
        val reelDataAdapter = MateriaAdapter(reelData, "reelData")
        rvReelList.adapter = reelDataAdapter
        if (reelData.isEmpty()) {
            reReel.visibility = View.GONE
        } else {
            reReel.visibility = View.VISIBLE
        }
        reelDataAdapter.setOnItemClickListener {data ->
            intent.putExtra("type", "materiaAdapter")
            intent.putExtra("materiaData", data)
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivity(intent)
        }

        val coverData = filteringData("cover")
        initRecyclerView(rvCoverList, this)
        val coverDataAdapter = MateriaAdapter(coverData, "coverData")
        rvCoverList.adapter = coverDataAdapter
        if (coverData.isEmpty()) {
            reCover.visibility = View.GONE
        } else {
            reCover.visibility = View.VISIBLE
        }
        coverDataAdapter.setOnItemClickListener {data ->
            intent.putExtra("type", "materiaAdapter")
            intent.putExtra("materiaData", data)
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivity(intent)
        }

        val plugData = filteringData("plug")
        initRecyclerView(rvPlugList, this)
        val plugDataAdapter = MateriaAdapter(plugData, "plugData")
        rvPlugList.adapter = plugDataAdapter
        if (plugData.isEmpty()) {
            rePlug.visibility = View.GONE
        } else {
            rePlug.visibility = View.VISIBLE
        }
        plugDataAdapter.setOnItemClickListener {data ->
            intent.putExtra("type", "materiaAdapter")
            intent.putExtra("materiaData", data)
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivity(intent)
        }

    }

    private fun lotMaterialsData(lotMaterialsList: ArrayList<BomBean.Materialslist>,lotID:String) {
        val carriertapeData = lotFilteringData("carriertape", lotMaterialsList)
        initRecyclerView(rvLotCarrierList, this)
        lotMateriaAdapter = LotMateriaAdapter(carriertapeData, "carriertapeData",lotID)
        rvLotCarrierList.adapter = lotMateriaAdapter
        if (carriertapeData.isEmpty()) {
            reLotCarriertape.visibility = View.GONE
        } else {
            reLotCarriertape.visibility = View.VISIBLE
        }

        val reelData = lotFilteringData("reel", lotMaterialsList)
        initRecyclerView(rvLotReelList, this)
        lotMateriaAdapter = LotMateriaAdapter(reelData, "reelData",lotID)
        rvLotReelList.adapter = lotMateriaAdapter
        if (reelData.isEmpty()) {
            reLotReel.visibility = View.GONE
        } else {
            reLotReel.visibility = View.VISIBLE
        }

        val coverData = lotFilteringData("cover", lotMaterialsList)
        initRecyclerView(rvLotCoverList, this)
        lotMateriaAdapter = LotMateriaAdapter(coverData, "coverData",lotID)
        rvLotCoverList.adapter = lotMateriaAdapter
        if (coverData.isEmpty()) {
            reLotCover.visibility = View.GONE
        } else {
            reLotCover.visibility = View.VISIBLE
        }

        val plugData = lotFilteringData("plug", lotMaterialsList)
        initRecyclerView(rvLotPlugList, this)
        lotMateriaAdapter = LotMateriaAdapter(plugData, "plugData",lotID)
        rvLotPlugList.adapter = lotMateriaAdapter
        if (plugData.isEmpty()) {
            reLotPlug.visibility = View.GONE
        } else {
            reLotPlug.visibility = View.VISIBLE
        }

    }

    protected fun initRecyclerView(recyclerView: RecyclerView, context: Context?) {
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.addItemDecoration(DividerItemDecoration(context, 1))
    }

    private fun filteringData(type: String): List<EqpMaterialsBean.Materialslist?> {
        val mEntity: MutableList<EqpMaterialsBean.Materialslist?> = ArrayList()

        when (type) {
            "carriertape" -> {
                for (s in Constant.eqpMaterialsBean!!.mMaterialslist!!) {
                    if (s!!.mMaterialId != null) {
                        val substring = s.mMaterialId!!.substring(0, 3)
                        val substring2 = s.mMaterialId!!.substring(0, 2)
                        if (substring.equals("A04") || substring2.equals("04")) {
                            mEntity.add(s)
                        }
                    }
                }
            }
            "reel" -> {

                for (s in Constant.eqpMaterialsBean!!.mMaterialslist!!) {
                    if (s!!.mMaterialId != null) {
                        val substring = s.mMaterialId!!.substring(0, 3)
                        val substring2 = s.mMaterialId!!.substring(0, 2)
                        if (substring.equals("A06") || substring2.equals("06")) {
                            mEntity.add(s)
                        }
                    }
                }
            }
            "cover" -> {
                for (s in Constant.eqpMaterialsBean!!.mMaterialslist!!) {
                    if (s!!.mMaterialId != null) {
                        val substring = s.mMaterialId!!.substring(0, 5)
                        val substring2 = s.mMaterialId!!.substring(0, 4)
                        if (substring.equals("A0500") || substring2.equals("0500")) {
                            mEntity.add(s)
                        }
                    }
                }
            }
            "plug" -> {
                for (s in Constant.eqpMaterialsBean!!.mMaterialslist!!) {
                    if (s!!.mMaterialId != null) {
                        val substring = s.mMaterialId!!.substring(3, 5)
                        val ss = s.mMaterialId!!.substring(0, 3)
                        val substring2 = s.mMaterialId!!.substring(2, 4)
                        val ss2 = s.mMaterialId!!.substring(0, 2)
                        if ((ss == "A05" && substring != "00") || (ss2 == "05" && substring2 != "00")) {
                            mEntity.add(s)
                        }
                    }
                }
            }
        }

        return mEntity
    }

    override fun onRestart() {
        super.onRestart()
        if (Constant.eqpid != ""){
            viewModel.defaultEqpMaterials(Constant.eqpid)
        }
    }

    private fun lotFilteringData(
        type: String,
        lotMaterialsList: ArrayList<BomBean.Materialslist>
    ): ArrayList<BomBean.Materialslist> {
        val mEntity: ArrayList<BomBean.Materialslist> = ArrayList()

        when (type) {
            "carriertape" -> {
                for (s in lotMaterialsList) {
                    if (s!!.mMaterialCode != null) {
                        val substring = s.mMaterialCode!!.substring(0, 3)
                        val substring2 = s.mMaterialCode!!.substring(0, 2)
                        if (substring.equals("A04") || substring2.equals("04")) {
                            mEntity.add(s)
                        }
                    }
                }
            }
            "reel" -> {

                for (s in lotMaterialsList) {
                    if (s!!.mMaterialCode != null) {
                        val substring = s.mMaterialCode!!.substring(0, 3)
                        val substring2 = s.mMaterialCode!!.substring(0, 2)
                        if (substring.equals("A06") || substring2.equals("06")) {
                            mEntity.add(s)
                        }
                    }
                }
            }
            "cover" -> {
                for (s in lotMaterialsList) {
                    if (s!!.mMaterialCode != null) {
                        val substring = s.mMaterialCode!!.substring(0, 5)
                        val substring2 = s.mMaterialCode!!.substring(0, 4)
                        if (substring.equals("A0500") || substring2.equals("0500")) {
                            mEntity.add(s)
                        }
                    }
                }
            }
            "plug" -> {
                for (s in lotMaterialsList) {
                    if (s!!.mMaterialCode != null) {
                        val substring = s.mMaterialCode!!.substring(3, 5)
                        val ss = s.mMaterialCode!!.substring(0, 3)
                        val substring2 = s.mMaterialCode!!.substring(2, 4)
                        val ss2 = s.mMaterialCode!!.substring(0, 2)
                        if ((ss == "A05" && substring != "00") || (ss2 == "05" && substring2 != "00")) {
                            mEntity.add(s)
                        }
                    }
                }
            }
        }

        return mEntity
    }


    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                1 -> {
                    intent.putExtra("lotList", lotLists)
                    intent.putExtra("CustomerName", CustomerName)
                    intent.putExtra("FactoryPackage", FactoryPackage)
                    intent.putExtra("CustomerDevice", CustomerDevice)
                    intent.putExtra("EquipmentName", tvHandle.text.toString())
                    intent.putExtra("EquipmentStatus", tvMESstate.text.toString())
                    intent.putExtra("LotId", lotid)
                    intent.putExtra("eqpId", etEqpId.text.toString())
                    intent.setClass(this, Startjob2Activity::class.java)
                    startActivity(intent)
                }
                108 -> {
                    finish()
                }
            }

        }

    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 520) {
            try {
                val view = window.decorView.findFocus() as EditText
                when (view) {
                    etEqpId -> {
                        etEqpId.setText("")
                    }
                    etLotId -> {
                        etLotId.setText("")
                    }
                    etLotsId -> {
                        etLotsId.setText("")
                    }
                }
            } catch (e: Exception){
                println(e.message)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeMessages(0)
    }

}